package com.cy.pj.eiems.service.impl;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cy.pj.eiems.Exception.ServiceException;
import com.cy.pj.eiems.dao.SysExamDao;
import com.cy.pj.eiems.entity.Question;
import com.cy.pj.eiems.entity.Score;
import com.cy.pj.eiems.service.SysExamService;
import com.cy.pj.eiems.vo.PageObject;



@Service
public class SysExamServiceImpl implements SysExamService {

	@Autowired
	private SysExamDao sysExamDao;

	/**
	 *潜在bug:
	 *	可能产生相同随机数!
	 */
	@Override
	public List<Question> findQuestions() {
		int count = sysExamDao.getCountofQuestions();
		// 往dao的参数 
		Integer[] rQN = new Integer[count];
		// 随机产生5个数字
		for(int i=0; i<5; i++) {
			rQN[i] = new Random().nextInt(count);
		}
		List<Question> list = sysExamDao.findQuestions(rQN);
		return list;
	}
	/**
	 * 存score
	 */
	@Override
	public int saveResults(String username, Integer score) {
		int rows = sysExamDao.insertScores(username,score);
		return rows;
	}

	/**
	 * 分页查询score信息
	 */
	@Override
	public PageObject<Score> findPageObjects(
			String name, Integer pageCurrent) {
		//1.验证参数合法性
		//1.1验证pageCurrent的合法性，
		//不合法抛出IllegalArgumentException异常
		if(pageCurrent==null||pageCurrent<1)
			throw new IllegalArgumentException("当前页码不正确");
		//2.基于条件查询总记录数
		//2.1) 执行查询
		int rowCount=sysExamDao.getRowCount(name);
		//2.2) 验证查询结果，假如结果为0不再执行如下操作
		if(rowCount==0)
			throw new ServiceException("系统没有查到对应记录");
		//3.基于条件查询当前页记录(pageSize定义为2)
		//3.1)定义pageSize
		int pageSize=3;
		//3.2)计算startIndex
		int startIndex=(pageCurrent-1)*pageSize;
		//3.3)执行当前数据的查询操作
		List<Score> records=
				sysExamDao.findPageObjects(name, startIndex, pageSize);
		//4.对分页信息以及当前页记录进行封装
		//4.1)构建PageObject对象
		PageObject<Score> pageObject=new PageObject<>(pageCurrent, pageSize, rowCount, records);
		//4.2)封装数据
		pageObject.setPageCurrent(pageCurrent);
		pageObject.setPageSize(pageSize);
		pageObject.setRowCount(rowCount);
		pageObject.setRecords(records);
		pageObject.setPageCount((rowCount-1)/pageSize+1);
		//5.返回封装结果。
		return pageObject;
	}











	//	@Override
	//	public int insertWrongQuestionIds(String username, Integer[] wrongResults, String[] wrongChoices) {
	//		int rows = 0;
	//		for (int i=0; i<wrongResults.length; i++) {
	//			sysExamDao.insertWrongQuestionIds(username, wrongResults[i], wrongChoices[i]);
	//			rows++;
	//		}
	//		System.out.println("这是存错题的service" + username);
	//		return rows;
	//	}





}
